<?php

defined('BASEPATH') OR exit('No direct script access allowed');

// This can be removed if you use __autoload() in config.php OR use Modular Extensions
require APPPATH . '/libraries/REST_Controller.php';

/**
 * 用户相关API接口（微信）
 *
 * @package         CodeIgniter
 * @subpackage      Rest Server
 * @category        Controller
 * @author          Phil Sturgeon, Chris Kacerguis
 * @license         MIT
 * @link            https://github.com/chriskacerguis/codeigniter-restserver
 */
class User extends REST_Controller {

    function __construct()
    {
        // Construct the parent class
        parent::__construct();

        // Configure limits on our controller methods
        // Ensure you have created the 'limits' table and enabled 'limits' within application/config/rest.php
        // $this->methods['user_get']['limit'] = 1; // 500 requests per hour per user/key
        // $this->methods['user_post']['limit'] = 100; // 100 requests per hour per user/key
        // $this->methods['user_delete']['limit'] = 50; // 50 requests per hour per user/key
    }

    /**
     * 注册操作
     */
    public function register_post()
    {
        $post = $this->post();
        if(empty($post)) {
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100001,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
        }

        $register = 1;//注册操作
        $area = '86';
        $phone = isset($post['phone'])?strtolower(trim($post['phone'])):'';
        $password = isset($post['password'])?trim($post['password']):'';
        $password2 = isset($post['password2'])?trim($post['password2']):'';
        $vaildCode = isset($post['vaildCode'])?strtolower(trim($post['vaildCode'])):'';
        $redirect = isset($post['redirect'])?$post['redirect']:'/';
        $platform = $this->config->item('platform');//平台
        $cooper = $this->config->item('cooper');;
        $comefrom = 2;//1pc  2手机
        $reg_flag = 1;//注册
        $lang = 'zh-cn';
        $datetime = date('Y-m-d H:i:s');

        $this->load->library('session');
        $sessid = $this->session->session_id;

        //链接redis
        $this->load->driver('cache');
        $this->cache->redis->is_supported();
        //微信
        $openid = $this->cache->redis->getClient()->get("$platform|WechatCallback|$sessid");
        if($openid==''){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100002,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
        }
        //检查数据合法性
        if(!regex($phone,'mobile')){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100003,
                $this->config->item('rest_message_field_name') => '请输入正确手机号码'
            ), REST_Controller::HTTP_OK);
        }
        if(!regex($password,'password')){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100004,
                $this->config->item('rest_message_field_name') => '密码长度为6-18个字节'
            ), REST_Controller::HTTP_OK);
        }
        if($password!=$password2){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100005,
                $this->config->item('rest_message_field_name') => '两次密码输入不一致'
            ), REST_Controller::HTTP_OK);
        }

        
        $type = 'reg';
        $smsKey = "$platform|AJAX|getSMSCode|$type|$area|$phone";
        $cacheData = $this->cache->redis->getClient(0)->get($smsKey);
        if(empty($cacheData)) {
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100006,
                $this->config->item('rest_message_field_name') => '短信验证码输入有误'
            ), REST_Controller::HTTP_OK);
        }
        $tmpArr = explode("|",$cacheData);
        if($vaildCode!=$tmpArr[0]){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100006,
                $this->config->item('rest_message_field_name') => '短信验证码输入有误'
            ), REST_Controller::HTTP_OK);
        }
        $this->load->model('user_model');
        $whereArr = array(
            'platform' => $platform,//平台
            'phone' => $phone,
        );
        $isExist = $this->user_model->getUserInfoByMulti($whereArr);
        if($isExist){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100007,
                $this->config->item('rest_message_field_name') => '此手机用户已经存在，请更换手机'
            ), REST_Controller::HTTP_OK);
        }
        $whereArr = array(
            'platform' => $platform,//平台
            'openid' => $openid,
        );
        $isExistWX = $this->user_model->getUserInfoByMulti($whereArr);
        if(!empty($isExistWX)){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100008,
                $this->config->item('rest_message_field_name') => '此微信号已经存在，请更换微信号'
            ), REST_Controller::HTTP_OK);
        }
        //删除短信验证码cache
        $this->cache->redis->delete($smsKey);
        //获取通行证
        $signmsg = strtoupper(md5($platform . $cooper . $this->config->item('cooper_key') . $phone));
        $ip = get_ip();
        $time = time();
        $token = $phone;
        $otpArr = array(
            'register' => $register,//注册操作
            'area' => $area,
            'phone' => $phone,
            'token' => $token,
            'password' => md5(md5($password.$ip.$time)),
            'time' => $time,
            'user_ip' => $ip,
            'signmsg' => $signmsg,
            'lang' => $lang,
            'comefrom' => $comefrom,
            'reg_flag' => $reg_flag,
            'openid' => $openid,
        );
        $this->load->library('passPort');
        $this->passport->setPlatform($platform);
        $this->passport->setCooper($cooper);
        $rs = $this->passport->getOtp($otpArr);
        //解析获取的结果
        $result = array();
        parse_str($rs, $result);
        //获取OTP成功
        if ($result['result'] == '1001') {
            //验证是否正确
            $verify_msg = strtoupper(md5($platform . $cooper . $token . '1001' . $result['otp'] . $this->config->item('cooper_key')));
            if($result['signmsg'] != $verify_msg) {
                $this->response(array(
                    $this->config->item('rest_status_field_name') => 100009,
                    $this->config->item('rest_message_field_name') => '获取通行证失败'
                ), REST_Controller::HTTP_OK);
            }
            $uid = $result['uid'];
            //登录验证
            $signmsg    =   strtoupper(md5($platform . $cooper . $this->config->item('cooper_key') . $token . $result['otp']));
            /***********注册记录LOG Start************/
            $regLogArr  =   array(
                'uid'           =>  $uid,
                'platform'      =>  $platform,
                'cooper'        =>  $cooper,
                'comefrom'      =>  $comefrom,//网站
                'system'        =>  getSystem(),
                'browser'       =>  getBrowser(),
                'ip'            =>  $ip,
                'create_time'   =>  $datetime,
            );
            $this->user_model->addRegLog($regLogArr);
			
			/***********推荐人 Start************/
			$this->load->library('Referrals');
			$this->load->config('ticket');
            $this->referrals->createInvite($uid,$openid);
	

            $data = array('platform'=>$platform,'cooper'=>$cooper,'otp'=>$result['otp'],'signmsg'=>$signmsg,'redirect'=>$redirect,'uid'=>$uid);
            
            $otp = $result['otp'];
            //使Access失效
            $this->passport->delAccess($otp);

            $userInfo = $this->user_model->getUserInfo(array('uid'=>$uid));
            //是否禁止帐号重复登录
            if($userInfo['online_flag']==1){
                $onlineArr = $this->passport->checkOnline($uid);
                if(!empty($onlineArr)) foreach($onlineArr as $items){
                    $this->passport->kickOffline($items['skey']);
                }
            }
            $ip = get_ip();
            $system = getSystem();
            $browser = getBrowser();
            $randPass = md5($this->passport->makeRandPassword());//取得随机密码[用于检验cookie中所存加密字符串正确性]
            // $this->passport->setExpire($userInfo['cache_expire']);//设置在线误操作过期时间
            $this->passport->saveOnlineInfo($uid, $randPass);
            //提出已经超时的用户
            $this->passport->deleteOverTime();
            /***********登录记录LOG Start************/
            $loginLog   =   array(
                    'uid' => $uid,
                    'cooper' => $cooper,
                    'comefrom' => 2,//1pc 2手机
                    'system' => $system,
                    'browser' => $browser,
                    'ip' => $ip,
                    'platform' => $platform,
                    'create_time' => $datetime,
            );
            $this->user_model->addLoginLog($loginLog);
            /***********登录记录LOG End************/
            $this->passport->setCookie('wcp_openid',$openid);
            $this->response(array($this->config->item('rest_status_field_name')=>0,'uid'=>$uid,'redirect'=>$redirect), REST_Controller::HTTP_OK);
        }else{
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100010,
                $this->config->item('rest_message_field_name') => '获取通行证失败['.$result['result'].']'
            ), REST_Controller::HTTP_OK);
        }
    }

    /**
     * 登陆操作
     * @return [type] [description]
     */
    public function login_post(){
        $post = $this->post();
        if(empty($post)) {
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100001,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
        }
        $password = isset($post['password'])?trim($post['password']):'';
        $redirect = isset($post['redirect'])?$post['redirect']:'/';
        $isFree = isset($post['isFree'])?$post['isFree']:0;
        $platform = $this->config->item('platform');
        $cooper = $this->config->item('cooper');
        $datetime = date('Y-m-d H:i:s');

        $this->load->library('session');
        $sessid = $this->session->session_id;
        
        //链接redis
        $this->load->driver('cache');
        $this->cache->redis->is_supported();
        //微信
        // echo "$platform|WechatCallback|$sessid";
        $openid = $this->cache->redis->getClient()->get("$platform|WechatCallback|$sessid");
        if($openid=='' || $password=='') {
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100002,
                $this->config->item('rest_message_field_name') => '无效请求'
            ), REST_Controller::HTTP_OK);
        }

        //获取账户信息
        $this->load->model('user_model');
        $whereArr = array(
            'platform' => $platform,//平台
            'openid' => $openid,
        );
        $userInfo = $this->user_model->getUserInfoByMulti($whereArr);
        if(empty($userInfo)){
            $this->lockUser($this->cache->redis,$platform,$openid);
        }
        // $this->cache->redis->delete("LOCKUSER|$platform|$openid");
        // $this->cache->redis->delete("USERERROR|$platform|$openid");
        $lockUser = $this->cache->redis->get("LOCKUSER|$platform|$openid");
        if($lockUser && $lockUser == 1){
            // $this->response(array(
            //     $this->config->item('rest_status_field_name') => 100011,
            //     $this->config->item('rest_message_field_name') => '操作频繁，请24小时后再试'
            // ), REST_Controller::HTTP_OK);
        }
        $uid = $userInfo['uid'];
        $phone = $userInfo['phone'];
        if(generatePassword($password,$userInfo['create_ip'],strtotime($userInfo['create_time'])) != $userInfo['password']){
            $this->lockUser($this->cache->redis,$platform,$openid);
        }
        $this->cache->redis->delete("USERERROR|$platform|$openid");
        $this->cache->redis->delete("LOCKUSER|$platform|$openid");
        if(!empty($userInfo) && $userInfo['block'] == 1){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100012,
                $this->config->item('rest_message_field_name') => '帐号已被冻结，请联系客服'
            ), REST_Controller::HTTP_OK);
        }
        //获取通行证
        $signmsg = strtoupper(md5($platform . $cooper . $this->config->item('cooper_key') . $phone));
        $ip = get_ip();
        $time = time();
        $token = $phone;
        $otpArr = array(
            'register' => 0,//登陆
            'phone' => $phone,
            'token' => $token,
            'time' => $time,
            'user_ip' => $ip,
            'signmsg' => $signmsg,
        );
        $this->load->library('passPort');
        $this->passport->setPlatform($platform);
        $this->passport->setCooper($cooper);
        $rs = $this->passport->getOtp($otpArr);
        //解析获取的结果
        $result = array();
        parse_str($rs, $result);
        //获取OTP成功
        if ($result['result'] == '1001') {
            //验证是否正确
            $verify_msg = strtoupper(md5($platform . $cooper . $token . '1001' . $result['otp'] . $this->config->item('cooper_key')));
            if($result['signmsg'] != $verify_msg) {
                $this->response(array(
                    $this->config->item('rest_status_field_name') => 100009,
                    $this->config->item('rest_message_field_name') => '获取通行证失败'
                ), REST_Controller::HTTP_OK);  
            }
            $uid = $result['uid'];
            $otp = $result['otp'];
            $redirect = ($redirect == '')?"/":urldecode($redirect);
            //使Access失效
            $this->passport->delAccess($otp);
            //是否禁止帐号重复登录
            if($userInfo['online_flag']==1){
                $onlineArr = $this->passport->checkOnline($uid);
                if(!empty($onlineArr)) foreach($onlineArr as $items){
                    $this->passport->kickOffline($items['skey']);
                }
            }
            $ip = get_ip();
            $system = getSystem();
            $browser = getBrowser();
            $randPass = md5($this->passport->makeRandPassword());//取得随机密码[用于检验cookie中所存加密字符串正确性]
            $this->passport->setExpire($userInfo['cache_expire']);//设置在线误操作过期时间
            $this->passport->saveOnlineInfo($uid, $randPass);
            //提出已经超时的用户
            $this->passport->deleteOverTime();
            /***********登录记录LOG Start************/
            $loginLog   =   array(
                    'uid' => $uid,
                    'cooper' => $cooper,
                    'comefrom' => 2,//1pc 2手机
                    'system' => $system,
                    'browser' => $browser,
                    'ip' => $ip,
                    'platform' => $platform,
                    'create_time' => $datetime,
            );
            $this->user_model->addLoginLog($loginLog);
            /***********登录记录LOG End************/
            $this->passport->setCookie('wcp_openid',$openid);
            if($isFree==1){//免密码登陆
                $data = array(
                    'login_flag' => 1
                );
                $whereArr = array(
                    'uid' => $uid
                );
                $rs = $this->user_model->updateUser($data,$whereArr);
            }
            $this->response(array($this->config->item('rest_status_field_name')=>0,'uid'=>$uid,'redirect'=>$redirect), REST_Controller::HTTP_OK);
        }else{
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100010,
                $this->config->item('rest_message_field_name') => '获取通行证失败['.$result['result'].']'
            ), REST_Controller::HTTP_OK);
        }
    }

    public function forgot_post(){
        $post = $this->post();
        $uid = trim($post['uid']);
        $vaildCode = trim($post['vaildCode']);
        $password = trim($post['password']);
        $this->load->model('user_model');
        $platform = $this->config->item('platform');//平台
        $whereArr = array(
            'platform' => $platform,//平台
            'uid' => $uid,
        );
        $userData = $this->user_model->getUserInfoByMulti($whereArr);
        if(empty($userData)){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100001,
                $this->config->item('rest_message_field_name') => '提交失败'
            ), REST_Controller::HTTP_OK);
        }
        $area = $userData['area'];
        $phone = $userData['phone'];
        //链接redis
        $this->load->driver('cache');
        $this->cache->redis->is_supported();
        $type = 'forgot';
        $smsKey = "$platform|AJAX|getSMSCode|$type|$area|$phone";
        $cacheData = $this->cache->redis->get($smsKey);
        if(empty($cacheData)) {
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100006,
                $this->config->item('rest_message_field_name') => '短信验证码输入有误'
            ), REST_Controller::HTTP_OK);
        }
        $tmpArr = explode("|",$cacheData);
        if($vaildCode!=$tmpArr[0]){
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100006,
                $this->config->item('rest_message_field_name') => '短信验证码输入有误'
            ), REST_Controller::HTTP_OK);
        }
        $md5pwd = generatePassword($password,$userData['create_ip'],strtotime($userData['create_time']));
        $data = array(
            'password' => $md5pwd
        );
        $whereArr = array(
            'platform' => $platform,//平台
            'uid' => $uid,
        );
        $rs = $this->user_model->updateUser($data,$whereArr);
        if($rs){
            $this->response(array($this->config->item('rest_status_field_name')=>0,'redirect'=>'/'), REST_Controller::HTTP_OK);
        }else{
            $this->response(array(
                $this->config->item('rest_status_field_name') => 100007,
                $this->config->item('rest_message_field_name') => '操作失败'
            ), REST_Controller::HTTP_OK);
        }

    }

    //锁屏
    public function logout_get(){
        $platform = $this->config->item('platform');
        $cooper = $this->config->item('cooper');
        $this->load->library('passPort');
        $this->passport->setPlatform($platform);
        $this->passport->setCooper($cooper);
        $this->passport->doLogout();
        $this->response(array($this->config->item('rest_status_field_name')=>0,'redirect'=>'/'), REST_Controller::HTTP_OK);
    }

    public function profile_get(){
        $this->load->library('passPort');
        $this->passport->setPlatform($this->config->item('platform'));//设置平台
    }



    //用户输入错误锁
    private function lockUser($redis,$platform,$unique){
        // //记录错误次数
        // $redis->increment("USERERROR|$platform|$unique");
        // $redis->expire("USERERROR|$platform|$unique",1*3600);
        // $errCount = $redis->get("USERERROR|$platform|$unique");
        // if($errCount>=5){
        //     //锁24小时
        //     $redis->save("LOCKUSER|$platform|$unique",1,24*3600);
        //     jsonReturn(-1,"操作频繁，请24小时后再试！");
        //     $this->response(array(
        //         $this->config->item('rest_status_field_name') => 100011,
        //         $this->config->item('rest_message_field_name') => '操作频繁，请24小时后再试'
        //     ), REST_Controller::HTTP_OK);
        // }else{
        //     $remainCount = 5-$errCount;
        //     $this->response(array(
        //         $this->config->item('rest_status_field_name') => 100011,
        //         $this->config->item('rest_message_field_name') => "用户名或者密码输入有误！错误次数还剩".$remainCount."次"
        //     ), REST_Controller::HTTP_OK);
        // }
        $this->response(array(
            $this->config->item('rest_status_field_name') => 100011,
            $this->config->item('rest_message_field_name') => "用户名或者密码输入有误！"
        ), REST_Controller::HTTP_OK);
    }

}
